package com.nerve.cloudoffice.web.action;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.nerve.cloudoffice.common.Reply;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.service.IMService;
import com.nerve.cloudoffice.service.impl.IMServiceImpl;
import com.nerve.cloudoffice.web.model.MessageModel;
import com.opensymphony.xwork2.ModelDriven;

@SuppressWarnings("serial")
public class IMAction extends NerveAction implements ModelDriven<MessageModel>{
	
	private IMService service = new IMServiceImpl();
	
	private MessageModel model = new MessageModel();
	
	public MessageModel getModel() {
		return model;
	}
	public void setModel(MessageModel model) {
		this.model = model;
	}

	public void send(){
		Reply re = new Reply();
		try{
			service.save(model);
			re.setMessage(SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			
			re.setError(true);
			re.setMessage(e);
		}
		
		json(re);
	}
	
	public void list(){
		Reply re = new Reply();
		try{
			service.get(model);
			re.setMessage(model.getMessageList());
		}catch(Exception e){
			e.printStackTrace();
			
			re.setError(true);
			re.setMessage(e);
		}
		
		json(re,new ValueFilter() {
			public Object process(Object arg0, String arg1, Object arg2) {
				if(arg1.equals("fromUser") || arg1.equals("toUser")){
					if(arg2 == null)
						return arg2;
					
					User u = (User)arg2;
					return u.getId() + " " + u.getName();
				}
				
				return arg2;
			}
		});
	}
}